
#include <stdbool.h>

#include <reg24lu1.h>

#include "keyboard.h"
#include "HIDDKeyboardDriver.h"
#include "lu1_bfb.h"

#include "debug.h"

unsigned char read_key(unsigned char i)
{
	switch (i) {
		case 0:
			if (SW1) {
				LED1_ON();
				return true;
			}				
			else 
				return false;
			break;
			
		case 1:
			if (SW2) {
				LED2_ON();
				return true;
			}
			else 
				return false;
			break;

		case 2:
			if (SW3) {
				LED1_OFF();
				return true;
			}
			else 
				return false;
			break;
		case 3:
			if (SW4) {
				LED2_OFF();
				return true;
			}
			else 
				return false;
			break;
		default:
			return 0;
	}
		
}




void keyboard_handle() 
{
    int i;

    
	unsigned char pressedKeys[NUM_KEYS];
	unsigned char pressedKeysSize = 0;
	unsigned char releasedKeys[NUM_KEYS];
	unsigned char releasedKeysSize = 0;
	
	// Monitor buttons
	for (i=0; i < NUM_KEYS ; i++) {

		// Check if button state has changed
		unsigned char isButtonPressed = read_key(i);
		if (isButtonPressed != keyStatus[i]) {
			LED1_TOGGLE();

			// Update button state
			if (!isButtonPressed) {

				// Key has been pressed
				keyStatus[i] = 0;
				pressedKeys[pressedKeysSize] = keyCodes[i];
				pressedKeysSize++;
//				HIDDKeyboardDriver_RemoteWakeUp();
			}
			else {

				// Key has been released
				keyStatus[i] = 1;
				releasedKeys[releasedKeysSize] = keyCodes[i];
				releasedKeysSize++;
			}
		}
		
	}

	
	DBG(("pressedKeysSize = %d\n",(int)pressedKeysSize));
	
	DBG(("releasedKeysSize = %d\n",(int)releasedKeysSize));
	// Update key status in the HID driver if necessary
	if ((pressedKeysSize != 0) || (releasedKeysSize != 0)) {

		unsigned char status;
		

		do {
			
			DBG(("Sending...\n"));
			status = HIDDKeyboardDriver_ChangeKeys(pressedKeys,
												   pressedKeysSize,
												   releasedKeys,
												   releasedKeysSize);
		}
		while (status != true);
	}
	

}
